import { _decorator, Asset, Component, director, instantiate, Node, Prefab, resources } from 'cc';
import { GameData } from './GameData';
const { ccclass, property } = _decorator;

@ccclass('UIManager')
export class UIManager {

    public static openData:any = {};

    /** 界面名称路径 */
    public static uiNamePath = {
        // popupComonTip: 'popupComonTip',
        // popupInvit: 'popupInvit',
        // popupInvitHistory: 'popupInvitHistory',
        // popupKefu: 'popupKefu',
        // popupMyInfo: 'popupMyInfo',
        // popupMyInvit: 'popupMyInvit',
        // popupRank: 'popupRank',
        // popupRule: 'popupRule',
        // popupSeting: 'popupSeting',
        // popupShopMang: 'popupShopMang',
        // popupShopNew: 'popupShopNew',
        // popupTask: 'popupTask',
        popupTip: 'popupTip',

        popupAnswer: "popupAnswer",
        popupAnswer2: "popupAnswer2",
        popupResult: "popupResult",
        popupOver: "popupOver",
    };
     /** 事件 */
     public static EEventName = {
        OPEN_UI: 'OPEN_UI',
        CLOSE_UI: 'CLOSE_UI',
    };

    // UI单例对象(私有化)
    private static instances = {};
    // 资源缓存
    private static assets = {};

    /**
     * 打开一个UI
     * @param uiName UI名称
     * @param callback 回调函数
     */
    public static async open(uiName: string, param:{} = null, callback?: Function) {
        if (!uiName || uiName === '') {return;}

        UIManager.openData = param;
        const uiPath = uiName;
        const arr = uiName.split('/');
        uiName = arr[arr.length - 1];
        console.log("打开面板  " + uiName);
        try {
            
            // 已有节点，重新显示
            let node: Node = UIManager.instances[uiName];
            if (node && node.getComponent && (node as any)._components) {
                node.active = true;
                UIManager.reshow(node, uiName);
                callback && callback(undefined, node);
                return node;
            }

            // 新建节点
            const asset: any = UIManager.assets[uiName] || await UIManager.loadRes(`ui/${uiPath}`, Prefab);
            UIManager.assets[uiName] = asset;
            node = instantiate(asset);
            UIManager.reshow(node, uiName);
            UIManager.instances[uiName] = node;
            callback && callback(undefined, node);
            return node;
        } catch (error) {
            callback ? callback(error) : console.error(error);
        }
    }

    /**
     * 关闭一个UI
     * @param uiName UI名称 | UI节点对象
     * @param callback 回调函数
     */
    public static close(uiName: string | Node, isDestroy: boolean = false) {
        let node: Node;

        // 获取节点
        if (typeof uiName === 'string') {
            const arr = uiName.split('/');
            uiName = arr[arr.length - 1];
            node = UIManager.instances[uiName];
        } else {
            node = uiName;
            uiName = node.name;
        }

        if (!node) {return null;}

        // 关闭节点
        node.active = !1;
        node.parent = null;
        if (isDestroy) {
            UIManager.instances[uiName] = undefined;
            node.destroy();
        }
        
        return isDestroy ? null : node;
    }
    
    /**
     * 加载动态资源
     * @param path 资源路径
     * @param assetType 资源类型
     */
    static loadRes(path: string, assetType: typeof Asset): Promise<Asset> {
        return new Promise((resolve, reject)=>{
            resources.load(path, assetType, (err, res)=>{
                if (err) {return reject(err);}
                return resolve(res);
            });
        });
    }

    /**
     * 加载Panel资源
     * @param uiName Panel资源路径
     * @param assetType 资源类型
     */
    static async loadResPanel(uiName: string, assetType: typeof Asset = Prefab): Promise<Asset> {
        const uiPath = uiName;
        const arr = uiName.split('/');
        uiName = arr[arr.length - 1];

        if (UIManager.assets[uiName]) { return UIManager.assets[uiName];}
        UIManager.assets[uiName] = await UIManager.loadRes(`ui/${uiPath}`, assetType);

        return UIManager.assets[uiName];
    }

    /** 重置节点层级和父节点 */
    private static reshow(node: Node, uiName: string) {
        node.parent = director.getScene().getChildByName('Canvas');
        node.setSiblingIndex(100);
    }

    public static showTip(str:string){
        GameData.tipStr = str;
        UIManager.open(UIManager.uiNamePath.popupTip)
    }
}


